package sskj.regulatory.presentation.screen.login

import android.animation.ObjectAnimator
import android.annotation.SuppressLint
import android.content.Intent
import android.net.Uri
import android.text.*
import android.text.style.AbsoluteSizeSpan
import android.util.Log
import android.view.View
import android.view.animation.LinearInterpolator
import com.qmui.arch.QMUIFragment
import com.qmuiteam.qmui.widget.dialog.QMUIDialog
import com.qmuiteam.qmui.widget.dialog.QMUITipDialog
import com.vondear.rxtools.RxActivityTool
import com.vondear.rxtools.RxAnimationTool
import com.vondear.rxtools.RxKeyboardTool
import kotlinx.android.synthetic.main.fragment_login.*
import kotlinx.android.synthetic.main.fragment_login.view.*
import kotlinx.android.synthetic.main.fragment_register.view.*
import sskj.regulatory.R
import sskj.regulatory.R.id.content
import sskj.regulatory.R.id.etPassword
import sskj.regulatory.presentation.base_mvp.base.BaseFragment
import sskj.regulatory.presentation.screen.forgetpas.ForgetpasFragment
import sskj.regulatory.presentation.screen.main.MainActivity
import sskj.regulatory.presentation.screen.register.RegisterFragment
import sskj.regulatory.presentation.screen.registerMakePas.RegisteMakePasFragment
import javax.inject.Inject


class LoginFragment : BaseFragment<LoginContract.View, LoginContract.Presenter>(), LoginContract.View {

    private val TAG = "LoginFragment"

    private var gotoHome: Boolean = false

    @Inject
    lateinit var mPresenter: LoginPresenter

    private var screenHeight: Int = 0//屏幕高度

    private var keyHeight: Int = 0 //软件盘弹起后所占高度

    override val layoutResId: Int = R.layout.fragment_login

    override fun initPresenter() = mPresenter

    override fun injectDependencies() {
        activityComponent.inject(this)
    }

    override fun onFetchTransitionConfig(): TransitionConfig {
        return SCALE_TRANSITION_CONFIG
    }

    override fun onBackPressed(): Boolean {
        getActivity()?.finish()
        System.exit(0)
        return false
    }

    override fun translucentFull(): Boolean = true

    override fun openHomeActivity() {
        view?.postDelayed({
            startActivity(Intent(context, MainActivity::class.java))
            activity.tipDialog?.dismiss()
            getActivity()?.finish()
        }, 1000)


    }

    override fun initView() {
        mPresenter.autoLogin()
        screenHeight = this.resources.displayMetrics.heightPixels //获取屏幕高度
        keyHeight = screenHeight / 3//弹起高度为屏幕高度的1/3
        initEvent()
        initHitView()
    }


    @SuppressLint("ResourceAsColor")
    private fun initHitView() {
        var ss: SpannableString = SpannableString("用户名/手机号码")
        val ass: AbsoluteSizeSpan = AbsoluteSizeSpan(14, true)

        ss.setSpan(ass, 0, ss.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        mCacheView.etMobile.hint = SpannedString(ss);
        mCacheView.etMobile.setHintTextColor(R.color.qmui_config_color_50_pure_black)

        ss = SpannableString("密码")
        ss.setSpan(ass, 0, ss.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

        mCacheView.etPassword.hint = SpannedString(ss);
        mCacheView.etPassword.setHintTextColor(R.color.qmui_config_color_50_pure_black)

    }


    private fun initEvent() {
        mCacheView.etMobile.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {

            }

            override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {

            }

            override fun afterTextChanged(s: Editable) {
                if (!TextUtils.isEmpty(s) && mCacheView.ivCleanPhone.visibility == View.GONE) {
                    mCacheView.ivCleanPhone.visibility = View.VISIBLE
                } else if (TextUtils.isEmpty(s)) {
                    mCacheView.ivCleanPhone.visibility = View.GONE
                }
            }
        })
        mCacheView.etPassword.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {

            }

            override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {

            }

            override fun afterTextChanged(s: Editable) {
                if (!TextUtils.isEmpty(s) && mCacheView.cleanPassword.visibility == View.GONE) {
                    mCacheView.cleanPassword.visibility = View.VISIBLE
                } else if (TextUtils.isEmpty(s)) {
                    mCacheView.cleanPassword.visibility = View.GONE
                }
                if (s.isEmpty())
                    return

            }
        })
        /**
         * 禁止键盘弹起的时候可以滚动
         */
        mCacheView.scrollView.setOnTouchListener { _, _ -> true }

        mCacheView.scrollView.addOnLayoutChangeListener { _, _, _, _, bottom, _, _, _, oldBottom ->
            /* old是改变前的左上右下坐标点值，没有old的是改变后的左上右下坐标点值
              现在认为只要控件将Activity向上推的高度超过了1/3屏幕高，就认为软键盘弹起*/
            if (oldBottom != 0 && bottom != 0 && oldBottom - bottom > keyHeight) {
                Log.e("wenzhihao", "up------>" + (oldBottom - bottom))
                val dist = (mCacheView.content.bottom - bottom).toFloat()
                if (dist > 0) {
                    val mAnimatorTranslateY = ObjectAnimator.ofFloat(mCacheView.content, "translationY", 0.0f, -dist)
                    mAnimatorTranslateY.duration = 300
                    mAnimatorTranslateY.interpolator = LinearInterpolator()
                    mAnimatorTranslateY.start()
                    RxAnimationTool.zoomIn(mCacheView.logo, 0.6f, dist)
                }
                mCacheView.service.visibility = View.INVISIBLE

            } else if (oldBottom != 0 && bottom != 0 && bottom - oldBottom > keyHeight) {
                Log.e("wenzhihao", "down------>" + (bottom - oldBottom))
                if (mCacheView.content.bottom - oldBottom > 0) {
                    val mAnimatorTranslateY = ObjectAnimator.ofFloat(mCacheView.content, "translationY", mCacheView.content.translationY, 0f)
                    mAnimatorTranslateY.duration = 300
                    mAnimatorTranslateY.interpolator = LinearInterpolator()
                    mAnimatorTranslateY.start()
                    //键盘收回后，logo恢复原来大小，位置同样回到初始位置
                    RxAnimationTool.zoomOut(mCacheView.logo, 0.6f)
                }
                mCacheView.service.visibility = View.VISIBLE
            }
        }

        mCacheView.btnLogin.setOnClickListener {
            RxKeyboardTool.hideSoftInput(getActivity())
            gotoHome = true
            mPresenter.makeLogin(mCacheView.etMobile.text.toString(), mCacheView.etPassword.text.toString())
        }
        mCacheView.ivCleanPhone.setOnClickListener { mCacheView.etMobile.setText("") }
        mCacheView.cleanPassword.setOnClickListener { mCacheView.etPassword.setText("") }

        mCacheView.ivShowPwd.setOnClickListener {
            if (mCacheView.etPassword.inputType != InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD) {
                mCacheView.etPassword.inputType = InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD
                mCacheView.ivShowPwd.setImageResource(R.drawable.pass_visuable)
            } else {
                mCacheView.etPassword.inputType = InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_VARIATION_PASSWORD
                mCacheView.ivShowPwd.setImageResource(R.drawable.pass_gone)
            }

            if (!TextUtils.isEmpty(etPassword.text))
                mCacheView.etPassword.setSelection(etPassword.text.length)
        }

        mCacheView.regist.setOnClickListener {
            gotoHome = false
            startFragment(RegisterFragment())
        }
        mCacheView.forgetPassword.setOnClickListener {
            gotoHome = false
            startFragment(ForgetpasFragment())
        }
    }


    override fun showError(message: String?) {
        QMUIDialog.MessageDialogBuilder(getActivity())
                .setTitle("错误提示")
                .setMessage(message)
                .addAction("确定") { dialog, _ -> dialog.dismiss() }
                .create(R.style.QMUI_Dialog).show()
    }

    override fun showLoading() {
        activity.tipDialog = QMUITipDialog.Builder(context)
                .setIconType(QMUITipDialog.Builder.ICON_TYPE_LOADING)
                .setTipWord("正在加载")
                .create()
        activity.tipDialog?.show()
    }

    override fun hideLoading() {
        activity.tipDialog?.dismiss()
    }


    override fun showTipDialogError(message: String?) {
        activity.tipDialog?.dismiss()

        activity.tipDialog = QMUITipDialog.Builder(context)
                .setIconType(QMUITipDialog.Builder.ICON_TYPE_FAIL)
                .setTipWord(message)
                .create()
        activity.tipDialog?.show()

        view?.postDelayed({
            activity.tipDialog?.dismiss()
        }, 1500)
    }

    override fun clearText() {
        mCacheView.etMobile.setText("")
    }

    override fun loginError(message: String?) {
        QMUIDialog.MessageDialogBuilder(getActivity())
                .setTitle("错误提示")
                .setMessage(message)
                .addAction("确定") { dialog, _ -> dialog.dismiss() }
                .create(R.style.QMUI_Dialog).show()
    }

}
